package com.snow.useviewdemo.base;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.fragment.app.Fragment;


import butterknife.ButterKnife;

/**
 * 基础Fragment
 */
public abstract class BaseFragment<T extends ViewDataBinding> extends Fragment {

    protected Context mContext;
    protected T mBinding;
    protected boolean isViewInitiated;
    protected boolean isVisibleToUser;
    protected boolean isDataInitiated;
    //是否需要懒加载，默认懒加载，若不需要懒加载，在onCreate的方法中将isLazyLoad设置为true
    protected boolean isLazyLoad;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View layoutView = inflater.inflate(getLayoutId(), container, false);
        mBinding = DataBindingUtil.bind(layoutView);
        mContext = getContext();
        ButterKnife.bind(this, layoutView);
        return layoutView;

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        isViewInitiated = true;
        prepareFetchData();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (!isLazyLoad) {
            this.isVisibleToUser = isVisibleToUser;
            prepareFetchData();
        }
    }

    /**
     * 子fragment可以强制刷新
     *
     * @return
     */
    public boolean prepareFetchData() {
        if (isLazyLoad && isViewInitiated) {
            setViewData();
            isDataInitiated = true;
            return true;
        } else {
            if (isVisibleToUser && isViewInitiated && !isDataInitiated) {
                setViewData();
                isDataInitiated = true;
                return true;
            }
        }
        return false;
    }

    protected abstract int getLayoutId();

    protected abstract void setViewData();

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}
